import os
import datetime
import re

def sanitize_filename(filename):
    """Sanitize filename to be used as an ID in markdown."""
    return re.sub(r'[^\w\-_\. ]', '_', filename)

def get_file_info(file_path):
    """Get file information including creation and modification dates."""
    stat = os.stat(file_path)
    created = datetime.datetime.fromtimestamp(stat.st_ctime).strftime('%Y-%m-%d')
    modified = datetime.datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d')
    return created, modified

def get_language_identifier(file_extension):
    """Map file extension to language identifier for syntax highlighting."""
    extension_map = {
        'py': 'python',
        'html': 'html',
        'cpp': 'cpp',
        'h': 'cpp',
        'md': 'markdown',
        'c': 'c',
        'js': 'javascript'
    }
    return extension_map.get(file_extension, file_extension)

def merge_repository(src_folder, output_filepath, filetypes="py,html,cpp,h,c,js"):
    # Ensure the output directory exists
    os.makedirs(os.path.dirname(output_filepath), exist_ok=True)

    # Convert filetypes string to a set for faster lookup
    allowed_extensions = set(filetypes.split(','))

    # Initialize the content with the title and TOC placeholder
    content = "# 代码转换 Code Repository Merged Document\n\n## Table of Contents\n\n"
    toc = []
    files_content = []

    # Walk through the source folder
    for root, _, files in os.walk(src_folder):
        for file in files:
            file_extension = file.split('.')[-1]
            if file_extension in allowed_extensions:
                file_path = os.path.join(root, file)
                relative_path = os.path.relpath(file_path, src_folder)
                sanitized_path = sanitize_filename(relative_path)

                # Add to Table of Contents
                toc.append(f"- [{relative_path}](#{sanitized_path})")

                # Get file information
                created, modified = get_file_info(file_path)

                # Prepare file content
                file_content = f"""
<details>
<summary><h3 id="{sanitized_path}">{relative_path}</h3></summary>

|||FILE_PATH: {relative_path}|||
|||FILE_TYPE: {file_extension.upper()}|||
|||CREATED: {created}|||
|||LAST_MODIFIED: {modified}|||

```{get_language_identifier(file_extension)}
{open(file_path, 'r').read()}
```

|||END_FILE|||

</details>
"""
                files_content.append(file_content)

    # Add TOC to content
    content += '\n'.join(toc) + '\n\n---\n\n'

    # Add files content
    content += '\n'.join(files_content)

    # Write the content to the output file
    with open(output_filepath, 'w') as f:
        f.write(content)

    print(f"Merged document has been created at: {output_filepath}")

# Example usage
if __name__ == "__main__":
    src_folder = "/path/to/your/repository"
    output_filepath = "/path/to/output/merged_repo.md"
    filetypes = "py,html,cpp,h,c,js,md"
    merge_repository(src_folder, output_filepath, filetypes)
